# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :order.py
# @Time      :2022/7/26 11:09
# @Author    :吕华龙
from flask import Blueprint, request, jsonify, g
from flask_restful import Api, Resource, reqparse

from models.model import Course, Stu, db, CourseOrder
from utils.jwt_tool import JWT_tool

order_bp = Blueprint("order_bp", __name__, url_prefix="/order")

api = Api(order_bp)

# @order_bp.before_request
# def stu_login():
#     req = reqparse.RequestParser()
#     req.add_argument("token", location='headers', help="token的错误")
#     # print("--------------------+++++++++++++++>>>>>>>>>",request.path)
#     args = req.parse_args()
#     j = JWT_tool()
#     payload = j.ver_token(args['token'])
#
#     if not (payload or request.path in ['/login']):
#         return jsonify({
#             "code": 400,
#             "msg": "用户未登录"
#         })
#     else:
#         g.stu = payload

from views.users import required_login


# 订单增删改查
class OrderView(Resource):
    @required_login
    def post(self):
        s_id = g.stu['id']
        req = reqparse.RequestParser()
        req.add_argument("c_id", help="大纲id错误")
        args = req.parse_args()
        print("获取的大纲的id", args['c_id'])
        # 查询大纲的单条信息
        cour_info = Course.query.filter(Course.id == args['c_id']).first()
        money1 = cour_info.money  # 大纲的价格

        # 查询用户的信息  余额
        stu_info = Stu.query.filter(Stu.id == s_id).first()
        money2 = stu_info.money  # 用户余额

        if money2 < money1:
            return jsonify({
                "code": 400,
                "msg": "请充QQ币"
            })
        money3 = money2 - money1
        # 特色课数量
        course_num1 = stu_info.course_num
        course_num1 += 1

        # 修改用户QQ币余额和特色课的数量
        Stu.query.filter(Stu.id == s_id).update({
            "money": money3,
            "course_num": course_num1
        })
        db.session.commit()
        # 查看是否有该订单
        couorde_info = CourseOrder.query.filter(CourseOrder.c_id == args['c_id'], CourseOrder.s_id == s_id).first()
        if couorde_info:
            return jsonify({
                "code": 200,
                "msg": "您有改订单，无法订购"
            })
        # 创建订单
        try:
            couord = CourseOrder(c_id=args['c_id'], s_id=s_id)
            db.session.add(couord)
            db.session.commit()
            print("订单添加成功")
            return jsonify({
                "code": 200,
                "msg": "订单创建成功"
            })
        except Exception as e:
            print("订单创建失败", e)
            return jsonify({
                "code": 400,
                "msg": "课程创建失败"
            })


# 创建路由
api.add_resource(OrderView, "/cou_order_url")
